<script setup>
import { ref, reactive, toRaw, computed, onMounted, watch } from "vue";
import { getGlobal } from "/lib/utils/global.js";
const global = getGlobal();

const _teamInfoItemReg = {
  // 队长信息正则
  name: "",
  // 性别
  gender: "^(男|女)$",
  // 微信号
  wechat: "",
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};
const _teacherItemReg = {
  // 指导老师信息正则
  // 姓名
  name: "",
  // 性别
  gender: "^(男|女)$",
  // 手机号
  phone: `^1\\d{10}$`,
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 职业名称
  job: "",
};

const _teamMemberItemReg = {
  // 姓名
  name: "",
  // 性别
  gender: "^(男|女)$",
  // 手机号
  phone: "^1\\d{10}$",
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const teamInfoItem = {
  // 队长信息
  name: "",
  // 性别
  gender: "",
  // 微信号
  wechat: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const teacherItem = {
  // 指导老师信息
  // 姓名
  name: "",
  // 性别
  gender: "",
  // 手机号
  phone: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 职业名称
  job: "",
};
// 团队队员信息
const teamMemberItem = {
  // 姓名
  name: "",
  // 性别
  gender: "",
  // 手机号
  phone: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const formData = reactive({
  agree: "", // 是否同意
  type: "", // 团队想要参加的类型 [1 花旗挑战 0 自选赛道]
  teamType: "", // 哪种 [1 人工智能-风险控制 2 VE（虚拟经济）]
  esgName: "", // ESG 项目名称
  vEName: "", // Vitual Economy项目名称
  projectName: "", // 项目名称
  teamName: "", // 团队名称
  teamPhone: "", // 团队队长手机号
  teamInfo: [{ ...teamInfoItem }],
  // 指导老师信息
  teacher: [{ ...teacherItem }],
  // 团队队员
  teamMember: [{ ...teamMemberItem }, { ...teamMemberItem }],
});

function addTeacher() {
  formData.teacher.push({ ...teacherItem });
}

function addTamMember() {
  formData.teamMember.push({ ...teamMemberItem });
}

// 本地缓存
watch(formData, (n) => {
  localStorage.setItem("formDataStore__HQB", JSON.stringify(n));
});

const formRef = ref(null);
const rawForm = toRaw(formData);
const qrcode_url = window.qrcode_url;
const csrf_token = window.csrf_token;
const formAction = window.formAction;
const formDefaultData = window.formDefaultData;

const showModal = ref(false);
function closeModal() {
  showModal.value = false;
}

function submit() {
  if (!checkForm()) {
    return;
  }
  formRef.value.submit();
}

const disabled = window.formDefaultData;
onMounted(async () => {
  if (formDefaultData) {
    Object.assign(formData, JSON.parse(formDefaultData));

    showModal.value = true;
    return;
  }
  const _formDataStore = localStorage.getItem("formDataStore__HQB");
  const formDataJson = JSON.parse(_formDataStore);
  if (_formDataStore) {
    const confirm = await global.$pop.alert(
      "你已经填写了部分信息<br/>是否继续填写?"
    );
    if (confirm) {
      Object.assign(formData, formDataJson);
    }
  }
});

const rawFormRef = ref();
function checkForm() {
  if (!rawFormRef.value.checkValidity()) {
    return false;
  }

  if (formData.agree === "") {
    global.$pop.toast({
      content: "请确认是否同意本次大赛及授权",
      style: { background: "orange" },
    });
    return false;
  }
  if (formData.type === "") {
    global.$pop.toast({
      content: "请选择你们团队想要参加的类型",
      style: { background: "orange" },
    });
    return false;
  }

  if (formData.type == "1" && formData.teamType === "") {
    global.$pop.toast({
      content: "请选择要参加的挑战",
      style: { background: "orange" },
    });
    return false;
  }
  if (
    formData.type == "1" &&
    formData.teamType == "1" &&
    formData.esgName === ""
  ) {
    global.$pop.toast({
      content: "请填写风险控制项目名称",
      style: { background: "orange" },
    });
    return false;
  }
  if (
    formData.type == "1" &&
    formData.teamType == "0" &&
    formData.vEName === ""
  ) {
    global.$pop.toast({
      content: "请填写幻觉偏差项目名称",
      style: { background: "orange" },
    });
    return false;
  }
  if (formData.type == "0" && formData.projectName === "") {
    global.$pop.toast({
      content: "请填写项目名称",
      style: { background: "orange" },
    });
    return false;
  }

  if (formData.teamName === "") {
    global.$pop.toast({
      content: "请选择你们的团队名称",
      style: { background: "orange" },
    });
    return false;
  }
  if (!/1\d{10}/.test(formData.teamPhone)) {
    global.$pop.toast({
      content: "团队队长手机号不规范",
      style: { background: "orange" },
    });
    return false;
  }

  let err = "";
  formData.teamInfo.forEach((item) => {
    if (!item.name) {
      err = "请填写队长姓名";
    }
    if (!item.gender) {
      err = "请填写队长性别";
    }
    if (!item.wechat) {
      err = "请填写队长微信";
    }
    if (!item.email) {
      err = "请填写队长邮箱";
    }
    if (!item.school) {
      err = "请填写队长高校名称";
    }
    if (!item.major) {
      err = "请填写队长专业名称";
    }
    if (!item.grade) {
      err = "请填写队长年级";
    }
  });
  if (err) {
    global.$pop.toast({ content: err, style: { background: "orange" } });
    return false;
  }

  formData.teacher.forEach((item) => {
    if (!item.name) {
      err = "请填写老师姓名";
    }
    if (!item.gender) {
      err = "请填写老师性别";
    }
    if (!item.phone) {
      err = "请填写老师手机号";
    }
    if (!item.email) {
      err = "请填写老师邮箱";
    }
    if (!item.school) {
      err = "请填写老师高校名称";
    }
    if (!item.job) {
      err = "请填写老师职务名称";
    }
  });

  if (err) {
    global.$pop.toast({ content: err, style: { background: "orange" } });
    return false;
  }

  formData.teamMember.forEach((item) => {
    if (!item.name) {
      err = "请填写团队成员姓名";
    }
    if (!item.gender) {
      err = "请填写团队成员性别";
    }
    if (!item.phone) {
      err = "请填写团队成员手机号";
    }
    if (!item.email) {
      err = "请填写团队成员邮箱";
    }
    if (!item.school) {
      err = "请填写团队成员高校名称";
    }
    if (!item.major) {
      err = "请填写团队成员专业名称";
    }
    if (!item.grade) {
      err = "请填写团队成员年级";
    }
  });

  if (err) {
    global.$pop.toast({ content: err, style: { background: "orange" } });
    return false;
  }
  return true;
}
</script>

<template>
  <div class="h-16 bg-blue-100"></div>

  <div class="p-4 bg-white">
    <div class="py-4 text-2xl text-center text-sky-500">
      2023-2024第十九届“花旗杯”金融创新应用大赛报名表
    </div>
    <div class="pb-4 border-b">
      亲爱的同学们，你们好！欢迎大家报名本次2023-2024第十九届“花旗杯”金融创新应用大赛活动！本报名表所填信息必须真实，请同学们务必认真填写，感谢大家的支持与配合！
      <!-- <span class="text-red-500">（填写报名表的过程中如遇任何问题，请添加工作人员微信 [微信号：EFG-GCC]）</span> -->
    </div>
    <form ref="rawFormRef" action="#" onsubmit="return false">
      <div class="py-4 space-y-8">
        <section>
          <div>
            1.请确认是否同意本次大赛出于花旗杯金融创新应用大赛之目的向花旗杯大赛组委会披露相关个人信息并同意花旗杯大赛组委会出于花旗杯金融创新应用大赛之目的进一步处理相关个人信息
            <div class="py-2 text-sm font-bold text-red-500">
              注意：如您未确认及授权，我们将视作无效报名！（所收集涉及到的个人信息仅限大赛方用于本次大赛报名及联络等相关事宜，不会对外公开）
            </div>
          </div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="a"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.agree"
                value="1"
              />
              是</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="a"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.agree"
                value="0"
              />
              否</label
            >
          </div>
        </section>

        <section>
          <div>2.你们团队想要参加的是：</div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="b"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.type"
                value="1"
              />
              花旗挑战</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="b"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.type"
                value="0"
              />
              自选赛道</label
            >
          </div>
        </section>

        <section v-if="formData.type != '' && formData.type != '0'">
          <div>3.你们团队想要参加下列那种（花旗挑战）：</div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.teamType"
                value="1"
              />
              人工智能-风险控制</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.teamType"
                value="0"
              />
              人工智能-幻觉偏差</label
            >
          </div>
        </section>

        <section
          v-if="
            formData.type != '' &&
            formData.type != '0' &&
            formData.teamType == '1'
          "
        >
          <div>4.你们团队的项目名称是【花旗挑战-人工智能-风险控制】：</div>
          <div class="flex flex-col mt-2">
            <input
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.esgName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section
          v-if="
            formData.type != '' &&
            formData.type != '0' &&
            formData.teamType == '0'
          "
        >
          <div>5.你们团队的项目名称是【花旗挑战-人工智能-幻觉偏差】：</div>
          <div class="flex flex-col mt-2">
            <input
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.vEName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section v-if="formData.type == '0'">
          <div>6.你们团队的项目名称是（自选赛道）：</div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.projectName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>7.你们的团队名称是：</div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.teamName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>
            8.你们团队队长的手机号码是：
            <div class="text-sm text-slate-500">
              该手机号将作为后续修改团队名单的验证号码，请大家慎重填写！
              <b class="text-red-500"
                >（注意：这里必须填写中国大陆手机号！！！）</b
              >
            </div>
          </div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^1\d{10}$"
              :disabled="disabled"
              type="text"
              v-model="formData.teamPhone"
              class="w-1/2 form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>9.团队队长信息</div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>微信号</th>
                  <th>邮箱地址</th>
                  <th>高校名称</th>
                  <th>专业名称</th>
                  <th>年级（如: 2023级大一）</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teamInfo" :key="i">
                  <td class="w-12 bg-slate-100">队长</td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teamInfoItemReg[n] || `^[\u4E00-\u9FA5A-Za-z0-9]+$`
                      "
                      :disabled="disabled"
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teamInfo[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>

        <section>
          <div>
            10.指导老师信息
            <div class="text-sm text-slate-500">
              （每个团队必须至少选择一名指导老师，但最多只可选择两名）
            </div>
          </div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>手机号</th>
                  <th>邮箱地址</th>
                  <th>在职高校名称</th>
                  <th>职务名称</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teacher" :key="i">
                  <td
                    class="flex items-center justify-center w-12 bg-slate-100"
                  >
                    <span
                      class="w-full text-white bg-red-500 border rounded cursor-pointer hover:bg-red-400"
                      v-if="i > 0"
                      @click="formData.teacher.splice(i, 1)"
                      >－</span
                    >
                    <span v-else>{{ i + 1 }}</span>
                  </td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teacherItemReg[n] || `^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$`
                      "
                      :disabled1="disabled"
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teacher[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div
            class="flex items-center justify-center mt-4"
            v-if="formData.teacher.length < 2"
          >
            <span
              class="flex items-center gap-2 p-2 px-8 border rounded cursor-pointer text-slate-500 hover:bg-slate-100"
              @click="addTeacher"
            >
              <span
                class="flex items-center justify-center w-5 h-5 text-white bg-blue-500 rounded-full"
                >＋</span
              >
              增加
            </span>
          </div>
        </section>

        <section>
          <div>
            11.团队队员信息
            <div class="text-sm text-slate-500">
              （每个团队除队长外，包含至少2名队员）
            </div>
          </div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>手机号</th>
                  <th>邮箱地址</th>
                  <th>高校名称</th>
                  <th>专业名称</th>
                  <th>年级（如: 2023级大一）</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teamMember" :key="i">
                  <td
                    class="flex items-center justify-center w-12 bg-slate-100"
                  >
                    <span
                      class="w-full text-white bg-red-500 border rounded cursor-pointer hover:bg-red-400"
                      v-if="i > 1"
                      @click="formData.teamMember.splice(i, 1)"
                      >－</span
                    >
                    <span v-else>{{ i + 1 }}</span>
                  </td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teamMemberItemReg[n] ||
                        `^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$`
                      "
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teamMember[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div
            class="flex items-center justify-center mt-4"
            v-if="formData.teamMember.length >= 2"
          >
            <span
              class="flex items-center gap-2 p-2 px-8 border rounded cursor-pointer text-slate-500 hover:bg-slate-100"
              @click="addTamMember"
            >
              <span
                class="flex items-center justify-center w-5 h-5 text-white bg-blue-500 rounded-full"
                >＋</span
              >
              增加
            </span>
          </div>
        </section>

        <div class="sticky bottom-0 pt-20 pb-8 text-center">
          <button
            class="px-20 py-3 m-auto text-white transition bg-blue-500 rounded hover:bg-blue-600"
            @click="submit"
          >
            提交
          </button>
        </div>
      </div>
    </form>

    <!-- 真正 POST 提交 -->
    <form
      ref="formRef"
      class="flex items-center justify-center mt-12"
      method="post"
      :action="formAction"
    >
      <input
        class="border"
        type="hidden"
        name="_csrf_token"
        :value="csrf_token"
      />
      <input
        name="formData"
        type="hidden"
        class="w-full border"
        :value="JSON.stringify(rawForm)"
      />
    </form>
  </div>

  <!-- 测试信息，打包后删除 -->
  <div class="sticky bottom-0 hidden px-4 mt-4 text-white bg-black/50">
    <div class="font-medium">formAction: {{ formAction }}</div>
    <div class="font-medium">csrf_token: {{ csrf_token }}</div>
    <div class="p-2 bg-red-400/50">
      formData
      <div class="p-2 border border-red-300">
        {{ formData }}
      </div>
    </div>
  </div>

  <!-- 报名成功后弹出的二维码 -->
  <div
    class="fixed top-0 left-0 flex items-center justify-center w-full h-full p-8 bg-black/50"
    v-if="showModal"
  >
    <div class="relative bg-white rounded">
      <div class="p-4 text-center text-slate-600">
        你的答卷已经提交，请<b class="font-bold text-slate-800">队长</b
        >扫描下方二维码进入参赛群！
      </div>
      <div class="p-4">
        <img
          :src="qrcode_url"
          class="object-contain p-2 m-auto border rounded border-black/5 bg-black/5 w-52 md:w-80"
        />
      </div>

      <div
        class="absolute cursor-pointer top-[calc(100%+20px)] left-0 w-full flex justify-center"
        @click="closeModal"
      >
        <span
          class="text-5xl transition text-white/80 hover:text-white hover:scale-110"
          >×</span
        >
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.form-radio-user {
  @apply border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50;
}

.form-input-user {
  @apply border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50 rounded transition;
}

.table-scroll {
  @apply text-sm text-center text-slate-500;

  .thead {
    @apply bg-slate-100;
  }

  .tbody {
    @apply bg-white;
  }

  th,
  td {
    @apply border;

    &:first-child {
      @apply sticky left-0 whitespace-nowrap p-2;
    }
  }

  th {
    @apply text-slate-500 whitespace-nowrap py-2 px-6;
  }

  td {
  }
}
</style>
